<template>
	<div class="withdraw-usdt flex-1 flex flex-col">
		<wallet-select-bank
			class="mx-[35px]"
			:options="list"
			modifyClass="bg-bg-3  pl-[12px]"
			v-model:modelValue="bankValue" />
		<div class="pb-[29px] pt-[10px] px-[35px] flex-1 flex flex-col">
			<div class="flex justify-between items-center">
				<div class="">{{ $t('withdraw.amount') }}</div>
				<div class="flex items-center text-sm text-t-2">
					{{ $t('withdraw.balance') }}:
					<base-currency v-if="currency" class="w-[18px]" :currency="currency" />
					<up-amount :value="balance" hideCurrency />
				</div>
			</div>
			<wallet-input-amount v-model:modelValue="amount" :max="balance" />
			<div class="mt-2 flex items-center text-sm">
				<div v-if="!limitError" class="items-center">
					<div class="flex items-center">
						{{ $t('withdraw.min') }}
						<base-currency v-if="currency" class="w-[18px]" :currency="currency" />
						<up-amount :value="usdtInfo.minAmount" hideCurrency />
					</div>
					<div class="flex items-center">
						{{ $t('withdraw.max') }}
						<base-currency v-if="currency" class="w-[18px]" :currency="currency" />
						<up-amount :value="usdtInfo.maxAmount" hideCurrency />
					</div>
				</div>
				<div v-else class="text-sm text-danger">
					<base-icon name="mistake" size="15" class="mr-1" />
					<template v-if="+amount < +balance">
						{{ $t('withdraw.limitError') }}
						（
						<up-amount :value="usdtInfo.minAmount" />
						~
						<up-amount :value="usdtInfo.maxAmount" />
						）
					</template>
					<template v-else>
						{{ $t('withdraw.limitError') }}
						(
						<up-amount :value="usdtInfo.minAmount" />
						~
						<up-amount :value="usdtInfo.maxAmount" />
						)
					</template>
				</div>
			</div>
			<div class="mt-1 flex items-center text-sm opacity-50">
				<template v-if="!isUSDTUser">
					{{ $t('withdraw.exchange') }}
					<img class="w-[14px] ml-1" src="@/assets/img/wallet-type/5.png" alt="" />
					1 ≈
					<base-currency v-if="currency" class="w-[18px]" :currency="currency" />
					<up-amount hideCurrency :value="usdtInfo.rate" />
					<span style="margin-right: 20px"></span>
				</template>
				<span class="flex items-center">
					{{ $t('withdraw.fee') }}
					<base-currency v-if="currency" class="w-[18px]" :currency="currency" />
					<up-amount hideCurrency :value="usdtInfo.gas" precision="2" />
				</span>
			</div>
			<div class="mt-1 flex items-center text-sm app-font-bold">
				{{ $t('withdraw.receipt') }}
				<img class="w-[14px] ml-1" src="@/assets/img/wallet-type/5.png" alt="" />
				<up-amount :value="receiptAmount" hideCurrency precision="2" />
			</div>

			<div class="flex-1" />

			<div class="mt-2 mb-[28px]">
				<base-button
					type="primary"
					block
					round
					:disabled="submitDisabled"
					:loading="loading"
					@click="onSubmit">
					{{ $t('withdraw.submit') }}
				</base-button>
			</div>

			<div class="mt-[18px]">
				<wallet-tip-desc type-code="WithdrawUsdt" />
			</div>
		</div>
	</div>

	<wallet-complete-dialog v-model="showDialog" />
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { useAppStore, useWalletStore } from '@/store'
import { WalletType } from '@/enums'
import { getWithdrawCryptoInfo, withdraw } from '@/api/wallet'
import { fmtMobile, showError, t } from '@/utils'
import WalletTipDesc from '@/views/wallet/components/wallet-tip-desc.vue'
import { HTTP_CODES } from '@/constants'
import WalletCompleteDialog from '@/views/wallet/components/wallet-complete-dialog.vue'
import { BaseButton, BaseCurrency, BaseIcon } from '@/components/base'
import { UpAmount } from '@/components/up'
import WalletInputAmount from '@/views/wallet/components/wallet-input-amount.vue'
import { WalletAction } from '@/types'
import WalletSelectBank from '@/views/wallet/components/wallet-select-bank.vue'

const appStore = useAppStore()
const walletStore = useWalletStore()

const addressId = ref(walletStore.withdrawData.id || walletStore.addresses[0]?.id)
// const addressId = ref(walletStore.addresses[0].id)

const currency = computed(() => appStore.currency)
const amount: any = ref('')
const balance = computed(() => walletStore.balance)
const isUSDTUser = computed(() => appStore.isUsdt)

const usdtInfo: any = ref({})

const limitError = computed(
	() =>
		amount.value &&
		(Number(amount.value) > Number(balance.value) ||
			Number(amount.value) < usdtInfo.value.minAmount ||
			Number(amount.value) > usdtInfo.value.maxAmount)
)

const submitDisabled = computed(() => !amount.value || limitError.value)

const loading = ref(false)
const showDialog = ref(false)
const withdrawAble = computed(() => walletStore.withdrawChannel.withdrawAble)
const onSubmit = async () => {
	try {
		loading.value = true
		// 因为金额到账到流水任务产品有一定的延迟，所以前端这里先做延迟 1000的提款处理
		setTimeout(async () => {
			await walletStore.getWithdrawChannel()
			if (!withdrawAble.value) {
				showDialog.value = true
				loading.value = false
				return false
			}
			const amountValue = +amount.value
			const params = {
				type: WalletType.usdt.id,
				walletId: addressId.value,
				balance: amountValue
			}
			await withdraw(params)
			// 提款完成之后立马清空输入框
			amount.value = ''
			loading.value = false
			console.log('WalletAction.withdraw.id', WalletAction.withdraw.id)
			walletStore.setWithdrawData({ resultId: WalletAction.withdraw.id, success: true })
			walletStore.setWithdrawResultPopupShow(true)
			walletStore.setWithdrawPopupShow(false)
		}, 1000)
	} catch (error: any) {
		loading.value = false
		if (error.code === HTTP_CODES.TurnoverNotAble) {
			return showError(t('httpCode[333]', { amount: 'fmtAmount(error.msg)' }))
		}
		if (error.code !== HTTP_CODES.TurnoverNotAble) {
			showError(error)
		}
	}
}

const list: any = computed(() =>
	walletStore.addresses.map((item: any) => ({
		id: item.id,
		text: item.crypto,
		content: fmtMobile(item.address, 9, 10),
		img: `wallet-type/${WalletType.usdt.id}.png`
	}))
)
console.log('(walletStore.addresses', walletStore.addresses)
const bankValue = ref(walletStore.withdrawData.usdtId)

const receiptAmount = computed(() => {
	if (!amount.value) return '0.00'
	let num = 0
	if (usdtInfo.value.rate) {
		num = amount.value / usdtInfo.value.rate - (usdtInfo.value.gas || 0)
	}
	const s = num.toFixed(2)
	return Number(s) <= 0 ? '0.00' : s
})
const getNetworkInfo = async () => {
	// let loading
	try {
		// loading = showLoading()
		const { data } = await getWithdrawCryptoInfo()
		// loading.close()
		usdtInfo.value = data
	} catch (error: any) {
		// loading.close()
		showError(error)
	}
}

onMounted(() => {
	getNetworkInfo()
})
</script>
<style lang="scss" scoped></style>
